<template>
  <div class="translate-view">
    <el-card class="full-height">
      <template #header>
        <div class="card-header">
          <h2>翻译练习</h2>
          <el-select
            v-model="translationType"
            placeholder="翻译类型"
            size="small"
          >
            <el-option label="英译中" value="ect"></el-option>
            <el-option label="中译英" value="cet"></el-option>
          </el-select>
        </div>
      </template>

      <div class="content">
        <div class="source-text">
          <h3>请翻译：</h3>
          <p>{{ translateQuestion.question }}</p>
          <el-collapse-transition>
            <p v-if="showAnswer" class="answer">
              答案: {{ translateQuestion.standardAnswer }}
            </p>
          </el-collapse-transition>
        </div>

        <el-form class="translation-form">
          <el-collapse-transition>
            <div v-if="showResult" class="result">
              <h3>翻译结果</h3>
              <el-progress
                :percentage="accuracy"
                :format="percentageFormat"
              ></el-progress>
              <ai-chat
                ><el-alert
                  title="翻译助手建议"
                  :description="suggestion"
                  type="info"
                  :closable="false"
                  show-icon
                ></el-alert
              ></ai-chat>
            </div>
          </el-collapse-transition>
          <el-form-item>
            <el-input
              type="textarea"
              :rows="4"
              v-model="userTranslation"
              placeholder="请输入您的翻译"
            ></el-input>
          </el-form-item>
        </el-form>

        <div class="button-container">
          <el-button type="info" @click="showHistory">历史记录</el-button>
          <div>
            <el-button type="primary" @click="refreshQuestion"
              >刷新问题</el-button
            >
            <el-button type="warning" @click="toggleAnswer">
              {{ showAnswer ? "隐藏答案" : "查看答案" }}
            </el-button>
            <el-button type="success" @click="submitTranslation"
              >提交翻译</el-button
            >
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import router from "@/router";
import { httpClient } from "@/libs/http-client";
import { SSE } from "sse.js";
import { useAuthStore } from "@/stores/auth";

const authStore = useAuthStore();

const translationType = ref("ect");
const userTranslation = ref("");
const showResult = ref(false);
const accuracy = ref(0);
const isCalculating = ref(false);
const suggestion = ref("");
const showAnswer = ref(false);
const translateQuestion = reactive({
  question: "正在个性化出题中...",
  standardAnswer: "",
});

onMounted(() => {
  // refreshQuestion();
});

const refreshQuestion = () => {
  showAnswer.value = false;
  // 调用后端API获取新的待翻译文本
  httpClient
    .get("translate/getOneQuestion", {
      params: { type: translationType.value },
    })
    .then((data) => {
      console.log(data);
      translateQuestion.question = data.question;
      translateQuestion.standardAnswer = data.standardAnswer;
      ElMessage.success("已刷新问题");
    });
  userTranslation.value = "";
  showResult.value = false;
};

const toggleAnswer = () => {
  showAnswer.value = !showAnswer.value;
};

const submitTranslation = () => {
  if (!userTranslation.value.trim()) {
    ElMessage.warning("请输入您的翻译");
    return;
  }

  isCalculating.value = true;
  accuracy.value = 0;
  suggestion.value = "等待响应中...";
  showResult.value = true;

  // 调用后端API进行翻译评估分数
  httpClient
    .post(
      "translate/calculateScore",
      {
        question: translateQuestion.question,
        standardAnswer: translateQuestion.standardAnswer,
        userAnswer: userTranslation.value,
      },
      {
        //配置超时时间
        timeout: 60000,
      }
    )
    .then((data) => {
      // 更新准确度
      accuracy.value = data.score;
      isCalculating.value = false;
    });

  // 调用后端API进行翻译评估
  // 创建 SSE 连接, 进行流式助理评价
  const evtSource = new SSE(
    "http://localhost:9090/translate/assistantSuggestion",
    {
      withCredentials: true,
      // 禁用自动启动，需要调用stream()方法才能发起请求
      start: false,
      // 携带token
      headers: {
        "Content-Type": "application/json",
        Authorization: authStore.token,
      },
      payload: JSON.stringify({
        question: translateQuestion.question,
        standardAnswer: translateQuestion.standardAnswer,
        userAnswer: userTranslation.value,
      }),
      method: "POST",
    }
  );
  evtSource.addEventListener("open", (event) => {
    console.log("SSE 连接已打开");
    suggestion.value = "";
  });
  evtSource.addEventListener("message", (event) => {
    const data = event.data;
    suggestion.value += JSON.parse(data).content;
  });
  evtSource.addEventListener("error", (event) => {
    console.error("SSE 连接错误:", event);
  });
  evtSource.addEventListener("close", (event) => {
    evtSource.close();
    console.log("SSE 连接已关闭");
    ElMessage.success("助理已完成");
  });

  evtSource.stream();

  ElMessage.success("翻译已提交");
};

const showHistory = () => {
  router.push({ path: "/translationHistory" });
};

const percentageFormat = (percentage) => {
  if (isCalculating.value) {
    return "准确度：计算中";
  }
  return `准确度：${percentage}%`;
};
</script>

<style scoped>
.translate-view {
  height: calc(100vh - 80px); /* 顶部有 80px 的间距 */
  padding: 20px;
  box-sizing: border-box;
}

.full-height {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-card ::v-deep(.el-card__body) {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.source-text {
  margin-bottom: 20px;
}

.translation-form {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.el-form-item {
  margin-bottom: 20px;
  align-items: flex-end;
  flex-direction: row;
}

.el-input {
  flex-grow: 1;
}

.el-textarea__inner {
  height: 100% !important;
}

.result {
  margin-top: 20px;
}

.el-select {
  width: 120px;
}

.button-container {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.answer {
  margin-top: 10px;
  font-style: italic;
  color: #409eff;
}
</style>
